﻿$(function () {
  var urlObj = {};
  var des, des2, deleteUrl, Name, Cname;
  urlObj.s = 0;
  urlObj.uType = 0;
  urlObj = getUrlParams();
  if (urlObj._id == undefined) urlObj._id = 'common';

  // 校验用户
  var userObj = localStorage.getItem('userObj') && localStorage.getItem('isLogin') ? JSON.parse(localStorage.getItem('userObj')): null;

  if(!userObj) {
    alert('你还没登录呢');
    setTimeout(()=>{window.location.href = '/login'},400);
  }else{
    $.get('../public/source/key.txt',data=>{
      var mainKey=data;
      if(userObj.adminKey != mainKey){
        alert('用户无权，申请管理员通过后，再次登录');
        setTimeout(()=>{window.location.href = '/'},400);
      }
    });
  }


  // 后台变化值
  if (urlObj.area == 1) {
    deleteUrl = `/node/deleteAnime`;
    des = '../public/img/index/anime/upload/';
    Name = 'Anime';
    Cname = '番剧';
  } else if (urlObj.area == 2) {
    deleteUrl = `/node/deleteGame`;
    des = '../public/img/index/game/upload/';
    Name = 'Game';
    Cname = '游戏';
  } else if (urlObj.area == 3) {
    deleteUrl = `/node/deleteMusic`;
    des = '../public/img/index/music/upload/';
    des2 = '../public/video/music/'
    Name = 'Music';
    Cname = '音乐';
  } else if (urlObj.area == 4) {
    deleteUrl = `/node/deleteNew`;
    des = '../public/img/index/new/upload/';
    Name = 'New';
    Cname = '资讯';
  } else if (urlObj.area == 5) {
    deleteUrl = `/node/deleteUser`;
    des = '../public/img/index/user/upload/';
    Name = 'User';
    Cname = '用户';
  }
  // 初始化
  // 初始化菜单选择
  var $navItem = $('.navItem').filter(function () { return $(this).attr('data-area') == urlObj.area });
  $navItem.addClass('active');
  $navItem.siblings().removeClass('active');
  // 初始化上传封面和小图
  $('.saveImg').attr('action', `/node/edit${Name}/upload?id=${urlObj._id}`);
  // 初始化标签默认样式
  $('.tagInput').val('');
  $('.tagInput').width('32');
  // 初始化选择默认
  var selectValue = $('#areaSelect').attr('data-value');
  $('#areaSelect option').each(function () {
    if ($(this).val() == selectValue) {
      $(this).attr('selected', 'selected')
    }
  });
  // 初始化排序方式
  var $item = $('#animeSearchSort .menuItem').filter((index, el) => (el.getAttribute('data-sort') == urlObj.s));
  $item.addClass('hide');
  $item.siblings().removeClass('hide');
  $('#animeSearchSort .select').html($item.html());

  var $item2 = $('#ueserSort .menuItem').filter((index, el) => (el.getAttribute('data-type') == urlObj.uType));
  $item2.addClass('hide');
  $item2.siblings().removeClass('hide');
  $('#ueserSort .select').html($item2.html());

  // 初始化 上传action
  $('#imgArrForm').attr('action', `/node/edit${Name}/upload?id=${urlObj._id}`);




  $('.navItem').click(function () {
    window.location.href = `/node?area=${$(this).attr('data-area')}&s=0&uType=0`
  })

  $('.moreButton').click(function () {
    $(this).prev('.content').addClass('auto');
    $(this).next('.lessButton').removeClass('hide');
    $(this).addClass('hide');
  });
  $('.lessButton').click(function () {
    $(this).prevAll('.content').removeClass('auto');
    $(this).addClass('hide');
    $(this).prev('.moreButton').removeClass('hide');
  });

  $('#addTag').click(function () {
    $(this).addClass('hide');
    $('#addTagOk').removeClass('hide');
    $('.tagInputC').removeClass('hide');
    $('.tagInput').focus();
  });

  $('#addTagOk').click(function () {
    var value = $('.tagInput').val();
    if (value) {
      // 创建标签到input
      var tags = [];
      var index = 0;
      // 判断是否有标签数组
      if ($('#tags').val()) {
        tags = JSON.parse($('#tags').val());
        index = tags.length;
      }
      tags.push($('.tagInput').val());
      $('#tags').val(JSON.stringify(tags));

      // 创建标签插入
      var tem = `<span class="tag tagNew" data-index="${index}">${value}<span class="deleteTag deleteTag1">x</span></span>`;
      $('.tagInputC').before(tem);

      // 样式变化
      $(this).addClass('hide');
      $('#addTag').removeClass('hide');
      $('.tagInputC').addClass('hide');

      $('.tagInput').val('');

    }
  });

  // 添加页面跳转
  $(`#add${Name}`).click(function () {
    window.location.href = `/node/add${Name}?area=${urlObj.area}`
  })

  // 删除操作
  $(`.delete${Name}`).click(function () {
    var id = $(this).attr('data-id');
    var title = $(this).attr('data-title');

    $('#deleteNotice').removeClass('hide');
    $('#blackBg').removeClass('hide');
    startMove(document.getElementById('deleteNotice'), { opacity: 100, top: 200 }, 1.05, function () {
      $('#deleteNotice h3').html(`删除${Cname} <span class="text-danger">${title}</span>, 将永不恢复...`)
      $('#deleteNotice input').val(id);
    });

  })



  $('#deleteNotice .cancel').click(function () {
    $('#deleteNotice h3').html(``)
    $('#deleteNotice input').val('');
    startMove(document.getElementById('deleteNotice'), { opacity: 0, top: 0 }, 1.05, function () {
      $('#deleteNotice').addClass('hide');
      $('#blackBg').addClass('hide');
    });

  })
  $('#deleteNotice .delete').click(function () {
    var id = $('#deleteNotice input').val();
    $('#deleteNotice h3').html(``)
    $('#deleteNotice input').val('');
    startMove(document.getElementById('deleteNotice'), { opacity: 0, top: 0 }, 1.05, function () {
      $('#deleteNotice').addClass('hide');
      $('#blackBg').addClass('hide');
      alert('删除成功');
      setTimeout(()=>{window.location.href = deleteUrl + `?_id=${id}`;},400);
    });

  })

  // 标签输入变化
  $(".tagInput").bind("input propertychange", function (e) {
    var value = $(this).val();
    var length = value.replace(/[\u0391-\uFFE5]/g, "aa").length;
    $(this).width(length * 7);
  });

  // 关闭编辑标签
  $('#closeAddTag').click(function () {
    $('#addTagOk').addClass('hide');
    $('#addTag').removeClass('hide');
    $('.tagInputC').addClass('hide');
  });


  // 初始渲染
  // 初始加载点击事件
  $('#tags_list').on("click", ".deleteTag1", function (e) {
    var target = $(e.target);
    var tags = JSON.parse($('#tags').val());
    var index = target.parent().attr('data-index');
    // 删除
    tags.splice(index, 1);
    target.parent().remove();
    if (tags.length == 0) {
      $('#tags').val('');
    } else {
      $('#tags').val(JSON.stringify(tags));
    }
  });



  // 保存事件
  $('.save').click(function () {
    alert('保存成功');
      setTimeout(()=>{history.go(0);},400);
  })
  $('.addSave').click(function () {
    alert('添加成功');
      setTimeout(()=>{toRrefresh();},400);
  
  })

  // 触发上传图片事件
  $('.imgSrc img').click(function () {
    $('#imgInput').click();
  })
  $('.imgSrc_F img').click(function () {
    $('#imgInput_F').click();
  })

  // 路径修改事件
  $('#imgInput').change(function () {
    var file = this.files[0];
    var url = des + urlObj._id + '/' + file.name;

    $('#imgInputText').val(`${url}`);
    $('.saveUpload').click();
    setTimeout(() => { $('.imgSrc img').attr('src', url) }, 1000);
  })
  $('#imgInput_F').change(function () {
    var file = this.files[0];
    var url = des + urlObj._id + '/' + file.name;
    $('#imgInputText_F').val(`${url}`);
    $('.saveUpload').click();
    setTimeout(() => { $('.imgSrc_F img').attr('src', url) }, 1000);
  })

  // 还原图片
  var imgSrc = $('#imgInputText').val();
  var imgSrc_F = $('#imgInputText_F').val();
  $('.return').click(function () {
    $('.imgSrc img').attr('src', imgSrc);
    $('#imgInputText').val(imgSrc);
  })
  $('.return_F').click(function () {
    $('.imgSrc_F img').attr('src', imgSrc_F);
    $('#imgInputText_F').val(imgSrc_F);
  })

  // 添加剧集，出现
  $('#addEpi').click(function () {
    $('#episodeAdd').removeClass('hide');
    $('#blackBg').removeClass('hide');
    $('#episodeAdd h2').html(`#${parseInt($(this).attr('data-length')) + 1} 添加剧集`);
    startMove(document.getElementById('episodeAdd'), { opacity: 100, top: 400 }, 1.15, function () {

    });

  })
  // 编辑剧集初始化
  $('.editEpi').click(function () {
    var arr = JSON.parse($(this).attr('data-value'));
    var index = $(this).attr('data-index');
    $('#episodeEdit h2').html(`#${index} ${arr.title} 剧集编辑`);
    $('#episodeEdit .eId').val(parseInt(index));
    $('#episodeEdit .titleE').val(arr.title);
    $('#episodeEdit .url').val(arr.url);
    $(`optionsRadios${arr.typeValue}`).prop('checked', 'true');
    $('#blackBg').removeClass('hide');
    $('#episodeEdit').removeClass('hide');
    startMove(getClass('episodeForm')[1], { opacity: 100, top: 400 }, 1.15, function () {

    });
  })
  // 添加、编辑剧集，关闭
  $('.episodeForm .closeAdd').click(function () {
    startMove(this.parentNode, { opacity: 0, top: 0 }, 1.15, function () {
      $(this).parent('.episodeForm').addClass('hide');
      $('#blackBg').addClass('hide');
    });

  })
  $('#addBtn').click(function () {
    startMove(this.parentNode, { opacity: 0, top: 0 }, 1.15, function () {
      $(this).parent('.episodeForm').addClass('hide')
      $('#blackBg').addClass('hide');
    });
    alert('添加成功');
      setTimeout(()=>{window.location.reload();},400);
  });
  $('#editBtn').click(function () {
    startMove(this.parentNode, { opacity: 0, top: 0 }, 1.15, function () {
      $(this).parent('.episodeForm').addClass('hide')
      $('#blackBg').addClass('hide');
    });
    alert('修改成功');
      setTimeout(()=>{window.location.reload();},400);

  });
  // 删除剧集反应
  $('.deleteEpi').click(function () {
    var id = $(this).attr('data-id');
    var title = $(this).attr('data-title');
    var index = $(this).attr('data-index');
    // 
    $('#deleteNotice2').removeClass('hide');
    $('#blackBg').removeClass('hide');
    startMove(document.getElementById('deleteNotice2'), { opacity: 100, top: 200 }, 1.05, function () {
      $('#deleteNotice2 h3').html(`删除剧集 <span class="text-danger">${title}</span>, 将永不恢复...`)
      $('#deleteNotice2 a').attr('href', `/node/episodes/delete?index=${index}&_id=${id}`);
    });

  });
  $('#deleteNotice2 .cancel').click(function () {
    startMove(document.getElementById('deleteNotice2'), { opacity: 0, top: 0 }, 1.05, function () {
      $('#deleteNotice2 h3').html(``)
      $('#deleteNotice2 a').attr('href', ``);
      $('#deleteNotice2').addClass('hide');
      $('#blackBg').addClass('hide');
    });
  })
  $('#deleteNotice2 .delete').click(function () {
    startMove(document.getElementById('deleteNotice2'), { opacity: 0, top: 0 }, 1.05, function () {
      $('#deleteNotice2 h3').html(``)
      $('#deleteNotice2 a').attr('href', ``);
      $('#deleteNotice2').addClass('hide');
      $('#blackBg').addClass('hide');
      alert('删除成功');
      setTimeout(()=>{window.location.reload();},400);
    });

  })

  // 番剧搜索
  $('.searchBtn').click(function () {
    window.location.href = `/node?area=${urlObj.area}&s=0&key=${$('#keyInput').val()}&uType=${urlObj.uType}`
  })
  // 监听搜索回车事件
  $('#keyInput').bind('keypress', function (event) {
    if (event.keyCode == "13") $('.searchBtn').click();
  });

  // 排序事件


  // 排序选择
  $('#animeSearchSort .menuItem').click(function () {
    var s = $(this).attr('data-sort');
    if (!urlObj.key) {
      urlObj.key = '';
    }
    window.location.href = `/node?key=${urlObj.key}&s=${s}&area=${urlObj.area}&uType=${urlObj.uType}`;
  })

  $('#ueserSort .menuItem').click(function () {
    var uType = $(this).attr('data-type');
    if (!urlObj.key) {
      urlObj.key = '';
    }
    window.location.href = `/node?key=${urlObj.key}&s=${urlObj.s}&area=${urlObj.area}&uType=${uType}`;
  })

  // 复选框事件(读取)
  $(".checkboxGroup Label input[type='checkbox']").filter(function () {
    var $this = $(this);
    return (
      $('.checkboxInput').val().indexOf($this.val()) != -1)
  }).attr('checked', 'checked'
  );
  // 复选框事件(修改)
  $(".checkboxGroup Label input[type='checkbox']").change(function () {
    var $this = $(this);
    if ($('.checkboxInput').val() == $this.val()) {
      $('.checkboxInput').val('');
    }
    else if ($('.checkboxInput').val() != '') {
      // 取消
      if ($('.checkboxInput').val().indexOf($this.val()) != -1) {
        // 不是最后面的
        if ($('.checkboxInput').val().indexOf($this.val() + '/') != -1) {
          $('.checkboxInput').val($('.checkboxInput').val().replace($this.val() + '/', ''));
        } else {
          $('.checkboxInput').val($('.checkboxInput').val().replace('/' + $this.val(), ''))
        }
      } else {
        // 选中
        $('.checkboxInput').val($('.checkboxInput').val() + '/' + $this.val())
      }

    } else {
      // 空选中
      $('.checkboxInput').val($('.checkboxInput').val() + $this.val())
    }
    console.log($('.checkboxInput').val());
  })


  // 添加游戏截图组事件
  $('.addImgArrBtn').click(function () {
    $('#imgArrForm').prepend(`<input class="imgArrFile" accept="image/png, image/jpeg, image/gif, image/jpg" type="file"  name="image${$('#imgArrForm .imgArrFile').length + 1}" >`);
    $('#imgArrForm .imgArrFile:first').click();
  })
  $('#imgArrForm').on(`click`, `.imgArrFile`, function () { })
  $('#imgArrForm').on(`change`, `.imgArrFile`, function () {
    var file = this.files[0];
    var url = des + urlObj._id + '/' + file.name;
    var imgArr = JSON.parse($('#imgArrInput').val());
    $('#imgArrSubmitBtn').click();
    $('#imgArrUl li').addClass('success');

    setTimeout(() => {
      if ($('.imgArrUl li').hasClass('noImgData')) {
        $('.imgArrUl').html(`<li><div class="imgCotanier"><img src="${url}"/><div class="blackBg"></div></div><span class="deleteImgArrBtn glyphicon glyphicon-remove" data-index=0></span><a href="${url}" target="_blank" class="lookUrl">
      <span class="glyphicon glyphicon-eye-open"> </span>
      <span class="text">预览</span>
    </a></li>`);
      } else {
        $('.imgArrUl').prepend(`<li><div class="imgCotanier"><img src="${url}"/><div class="blackBg"></div></div><span class="deleteImgArrBtn glyphicon glyphicon-remove" data-index=${$('#imgArrForm .imgArrFile').length}></span><a href="${url}" target="_blank" class="lookUrl">
      <span class="glyphicon glyphicon-eye-open"> </span>
      <span class="text">预览</span>
     </a></li>`);
      }
    }, 1000);

    imgArr.unshift(`${url}`);

    $('#imgArrInput').val(JSON.stringify(imgArr));
  })

  // 删除游戏截图组事件
  $(".imgArrUl").on("click", ".deleteImgArrBtn", function (e) {
    var $target = $(e.target);
    var index = $target.attr('data-index');
    var imgArr = JSON.parse($('#imgArrInput').val());
    if ($('.imgArrUl li').length == 1) {
      $('.imgArrUl').prepend(`<li class="noImgData"><div class="imgCotanier"><img src="../public/img/index/other/noImg.jpg"/></div><span class="deleteImgArrBtn glyphicon glyphicon-remove vhidden"></span></li>`);
    }
    imgArr.splice(index, 1);
    $('#imgArrInput').val(JSON.stringify(imgArr));
    $target.parent().remove();
    $('#imgArrForm .imgArrFile').eq(index).remove();
  })

  // 清除游戏截图事件
  $(".clearImgArrBtn").click(function () {
    // 清除图片和上传file
    $('.imgArrUl li').remove();
    $('#imgArrForm .imgArrFile').remove();
    $('.imgArrUl').prepend(`<li class="noImgData"><div class="imgCotanier"><img src="../public/img/index/other/noImg.jpg"/></div><span class="deleteImgArrBtn glyphicon glyphicon-remove vhidden"></span></li>`);
    $('#imgArrInput').val('[]');
  })


  // 隐藏列表
  $('.moveDown').click(function () {
    $('#musicArea').slideUp(500, () => { $('.moveUp').slideDown(100) });
  })
  $('.moveUp').click(function () {
    $(this).slideUp(100, () => { $('#musicArea').slideDown(500) });
  })
  // node音乐点击播放
  // 初始化
  var $audio = $("audio")[0];
  var musicIndex = 0;

  // 播放按钮
  var lyric;

  $('.tx').click(function () {
    //$('.moveUp').slideUp(100,()=>{$('#musicArea').slideDown(500)});
    var data = $(this).attr('data-all');
    var { musicUrl, imgSrc, singer, title, album, LyricsUrl } = JSON.parse(data);

    musicIndex = $(this).attr('data-index');

    // 获取歌词
    lyric = new Lyric(LyricsUrl);
    var $lryicContainer = $(".lycList");
    // 清空上一首音乐歌词
    $lryicContainer.html("");
    lyric.loadLyric(function () {
      // 创建歌词列表
      $.each(lyric.lyrics, function (index, ele) {
        var $item = $("<span class='lycLess'>" + ele + "</span>");
        $lryicContainer.append($item);
      });
    });

    // 渲染播放页面
    $('.musicTitle').html(`${title} - ${singer}`);
    $('.imgDiv img').attr('src', imgSrc);
    $('.album').html(`${album}`);
    $('.moveUp span').html(`${title} - ${singer}`);
    $('.imgBlackBg').attr('style', `background:url(${imgSrc})`);

    // 清楚其他音乐状态
    $(this).parents('tr').siblings().find('.player').removeClass('glyphicon-pause');
    $(this).parents('tr').siblings().find('.playerCotainer').css('display', '');

    if ($('#player_iframe').attr('src') !== musicUrl) {
      $('#player_iframe').attr('src', musicUrl);
    }
    if ($(this).find('.player').hasClass('glyphicon-pause')) { // 暂停
      $(this).find('.player').removeClass('glyphicon-pause');
      $('.playerIcon').removeClass('glyphicon-pause');
      $('.imgDiv img').removeClass('run');
      $audio.pause();
    } else { // 播放
      $(this).children('.playerCotainer').css('display', 'block');
      $(this).find('.player').addClass('glyphicon-pause');
      $('.imgDiv img').addClass('run');
      $('.playerIcon').addClass('glyphicon-pause');
      $audio.play();
    }
  })
  // 默认渲染播放器
  if (urlObj.area == 3) {
    $('.tx').eq(0).click();
    $('.tx').eq(0).children('.playerCotainer').css('display', '');
    $('.tx').eq(0).find('.player').removeClass('glyphicon-pause');
    $('.playerIcon').removeClass('glyphicon-pause');
    $('.imgDiv img').removeClass('run');
    $audio.pause();
  }

  $('.playerIcon').click(function () {
    if ($(this).hasClass('glyphicon-pause')) {
      // 暂停
      $('.player').eq(musicIndex).removeClass('glyphicon-pause');
      $('.playerIcon').removeClass('glyphicon-pause');
      $('.imgDiv img').removeClass('run');
      $audio.pause();
    } else { // 播放
      $('.playerCotainer').eq(musicIndex).css('display', 'block');
      $('.player').eq(musicIndex).addClass('glyphicon-pause');
      $('.playerIcon').addClass('glyphicon-pause');
      $('.imgDiv img').addClass('run');
      $audio.play();
    }
  })

  // 音量设置
  $('.musicVoiceIcon').click(function () {
    var volume = parseFloat($(this).attr('data-volume')).toFixed(1);
    if ($('.musicVoiceArea').css('display') == 'none') {
      $('.musicVoiceArea').slideDown(300, () => { $('.voiceProgress').slideDown(200) });
    } else {
      // 静音
      if (!$audio.muted) {
        $('.musicVoiceIcon').attr('class', 'musicVoiceIcon glyphicon glyphicon glyphicon-volume-off');
        $audio.muted = true;
        $('.voiceProgressC').height(0);
      } else {
        if (volume == 1) {
          $('.musicVoiceIcon').attr('class', 'musicVoiceIcon glyphicon glyphicon glyphicon-volume-up');
        } else {
          $('.musicVoiceIcon').attr('class', 'musicVoiceIcon glyphicon glyphicon glyphicon-volume-down');
        }
        $audio.muted = false;
        $audio.volume = volume;
        $('.voiceProgressC').height(`${85 * volume}%`);
      }
    }
  })
  $(document).bind('click', function (e) {
    var targert = e.target;
    if ($(targert).closest('.musicVoice').length == 0) {
      $('.voiceProgress').slideUp(200, () => { $('.musicVoiceArea').slideUp(300) });
    }
  })

  // 音乐滚动条
  // 点击滚动条
  $('.voiceProgress').click(function (e) {
    var allHeight = $(this).height();
    var thisY = $(this).offset().top
    var offsetY = e.originalEvent.clientY;
    var scale = parseFloat(1 - (offsetY - thisY) / allHeight).toFixed(1);
    if (scale >= 0.9) {
      $('.musicVoiceIcon').attr('class', 'musicVoiceIcon glyphicon glyphicon glyphicon-volume-up');
      $audio.muted = false;
      $audio.volume = 1;
      $('.musicVoiceIcon').attr('data-volume', 1);
      $('.voiceProgressC').height(`85%`);
    } else if (scale < 0.1) {
      $('.musicVoiceIcon').attr('class', 'musicVoiceIcon glyphicon glyphicon glyphicon-volume-off');
      $audio.muted = true;
      $('.voiceProgressC').height(0);
    } else {
      $('.musicVoiceIcon').attr('class', 'musicVoiceIcon glyphicon glyphicon glyphicon-volume-down');
      $audio.muted = false;
      $audio.volume = scale;
      $('.musicVoiceIcon').attr('data-volume', scale);
      $('.voiceProgressC').height(`${85 * scale}%`);
    }
  });
  // 按下
  // 监听鼠标的按下事件
  $('.voiceProgress').mousedown(function () {
    var $this = $('.voiceProgress');
    var normalTop = $this.offset().top;
    var barHeight = $this.height();
    var eventTop;
    // 监听鼠标的移动事件
    $(document).mousemove(function (event) {
      // 获取点击的位置距离窗口的位置
      eventTop = event.pageY;
      var offset = barHeight - (eventTop - normalTop);
      var volume = (parseInt(offset) / 100).toFixed(1);
      if (offset > 0.1 && offset <= barHeight) {
        $('.voiceProgressC').height(`${offset * 0.85}%`);
        $('.musicVoiceIcon').attr('class', 'musicVoiceIcon glyphicon glyphicon glyphicon-volume-down');
        $audio.muted = false;
        $audio.volume = volume;
        $('.musicVoiceIcon').attr('data-volume', volume);
      } else if (offset <= 0.1) {
        $('.voiceProgressC').height(0);
        $('.musicVoiceIcon').attr('class', 'musicVoiceIcon glyphicon glyphicon glyphicon-volume-off');
        $audio.muted = true;
      } else {
        $('.voiceProgressC').height(`85%`);
        $audio.muted = false;
        $('.musicVoiceIcon').attr('data-volume', 1);
        $('.musicVoiceIcon').attr('class', 'musicVoiceIcon glyphicon glyphicon glyphicon-volume-up');
        $audio.volume = 1;
      }

    })

    // 监听鼠标的抬起事件
    $(document).mouseup(function () {
      $(document).off("mousemove");
      $(document).off("mouseup");
    });
  })


  // 监听载入音乐
  // 时间全长
  var allTime;
  if (urlObj.area == 3) {
    $audio.addEventListener('durationchange', function () {
      allTime = $audio.duration;
      $('.musicTime .allTime').html(`${addZero(floor(allTime / 60))}:${addZero(floor(allTime % 60))}`);
    })
    // 监听实时播放
    // 时间播放时长
    $audio.addEventListener('timeupdate', function () {
      if (eval($('.progress').attr('isMove'))) return;
      var time = $audio.currentTime;
      var scale = time / allTime;
      if (scale) $('.progress_bar').width(`${scale * 100}%`)
      $('.musicTime .nowTime').html(`${addZero(floor(time / 60))}:${addZero(floor(time % 60))}`);

      // 实现歌词同步
      var index = lyric.currentIndex(time).index;
      var realIndex = lyric.currentIndex(time).realIndex;

      var $item = $(".lycList span").eq(realIndex);
      $item.addClass("lycMore");
      $item.siblings().removeClass("lycMore");

      //极简
      if (index >= 0) {
        $('.moveUp span').html(`${lyric.lyrics[realIndex]} (${$('.musicTitle').html()})`);
      }

      if (index < 2) {
        $(".lycList").animate({ top: 0 }, 100);
      } else {
        $(".lycList").animate({
          top: (-index + 2) * 30
        }, 100);
      }

    })
  }


  // 点击进度条播放
  $('.progress').click(function (e) {
    if (eval($(this).attr('isMove'))) return;
    var w = $('.progress').width();
    var x = e.originalEvent.layerX;
    var scale = x / w;
    if (x > 0) {
      $audio.currentTime = scale * allTime;
    } else {
      x = 0; scale = x / w;
      $audio.currentTime = scale * allTime;
    }
  })
  // 监听鼠标的按下事件
  $('.progress').mousedown(function () {
    var $this = $('.progress');
    $this.attr('isMove', true);
    var normalLeft = $this.offset().left;
    var barWidth = $this.width();
    var eventLeft;
    // 监听鼠标的移动事件
    $(document).mousemove(function (event) {
      // 获取点击的位置距离窗口的位置
      eventLeft = event.pageX;
      var offset = eventLeft - normalLeft;
      time = offset / barWidth * allTime;
      if (offset >= 0 && offset <= barWidth) {
        $('.progress_bar').width(offset);
        $('.musicTime .nowTime').html(`${addZero(floor(time / 60))}:${addZero(floor(time % 60))}`);
      } else if (offset < 0) {
        $('.progress_bar').width(0);
        $('.musicTime .nowTime').html(`00:00`);
      } else {
        $('.progress_bar').width('100%');
        $('.musicTime .nowTime').html(`${addZero(floor(allTime / 60))}:${addZero(floor(allTime % 60))}`);
      }

    })

    // 监听鼠标的抬起事件
    $(document).mouseup(function () {
      $(document).off("mousemove");

      var scale = $('.progress_bar').width() / $('.progress').width();
      $audio.currentTime = scale * allTime;
      $this.attr('isMove', false);

      $(document).off("mouseup");
    });
  })

  // 音乐添加界面显示
  $('#showAddMusic').click(function () {
    $('#addMusicForm').attr('action', `/node/addMusic`);
    $('#addMusicForm .tableTitle').html('音乐添加');
    $('#addMusicForm #title').val('');
    $('#addMusicForm #time').val('00:00');
    $('#addMusicForm #singer').val('');
    $('#addMusicForm #album').val('');
    $('#addMusicForm #areaSelect').val('中文');
    $('#addMusicForm #year').val(2019);
    $('#addMusicForm #month').val(1);
    $('#addMusicForm #day').val(1);
    $('#addMusicForm #zValue').val('');
    $('#addMusicForm #musicUrl').val('');
    $('#addMusicForm #LyricsUrl').val('');
    $('#addMusicForm #imgSrc').val('../public/img/index/other/noImg.jpg');
    $('#uploadMusic').val('');
    $('#addMusicForm .imgSrc img').attr('src', '../public/img/index/other/noImg.jpg');


    $('#addMusicForm').removeClass('hide');
    $('#blackBg').removeClass('hide');
    $('.progressM').removeClass('hide');
    startMove(document.getElementById('addMusicForm'), { opacity: 100, top: 400 }, 1.15, function () {

    });
  })
  $('.editMusic').click(function () {
    var music = JSON.parse($(this).attr('data-all'));
    console.log();

    $('#addMusicForm').attr('action', `/node/editMusic?_id=${music._id}`);
    $('#addMusicForm .tableTitle').html(`${music.title} 音乐编辑`);
    $('#addMusicForm #title').val(music.title);
    $('#addMusicForm #singer').val(music.singer);
    $('#addMusicForm #album').val(music.album);
    $('#addMusicForm #time').val(music.time);
    $('#addMusicForm #areaSelect').val(music.area);
    $('#addMusicForm #year').val(music.year);
    $('#addMusicForm #month').val(music.month);
    $('#addMusicForm #day').val(music.day);
    $('#addMusicForm #zValue').val(music.zValue);
    $('#addMusicForm #musicUrl').val(music.musicUrl);
    $('#addMusicForm #LyricsUrl').val(music.LyricsUrl);
    $('#addMusicForm #imgSrc').val(music.imgSrc);
    $('#addMusicForm .imgSrc img').attr('src', music.imgSrc);
    $('#uploadMusic').val('');

    $('#addMusicForm').removeClass('hide');
    $('#blackBg').removeClass('hide');
    $('.progressM').removeClass('hide');
    startMove(document.getElementById('addMusicForm'), { opacity: 100, top: 400 }, 1.15, function () {

    });
  })

  // 音乐界面消失
  $('#addMusicForm .closeAdd').click(function () {
    startMove(this.parentNode, { opacity: 0, top: 0 }, 1.15, function () {
      $('#addMusicForm').addClass('hide');
      $('.progressM').addClass('hide');
      $('#blackBg').addClass('hide');
    });

  })
  $('#addMusicForm #saveMusic').click(function () {
    startMove(this.parentNode, { opacity: 0, top: 0 }, 1.15, function () {
      $('#addMusicForm').addClass('hide');
      $('.progressM').addClass('hide');
      $('#blackBg').addClass('hide');
      alert('保存成功');
      setTimeout(()=>{history.go(0);},400);
    });

  })


  // 点击音乐图片上传
  $('#addMusicForm .imgC').click(function () {
    $('#uploadMusic').attr('data-accept', 'image');
    $('#uploadMusic').click();
  })
  // 点击音乐歌曲上传
  $('#addMusicForm #musicUrl').click(function () {
    $('#uploadMusic').attr('data-accept', 'audio');
    $('#uploadMusic').click();
  })
  // 点击音乐歌词上传
  $('#addMusicForm #LyricsUrl').click(function () {
    $('#uploadMusic').attr('data-accept', 'text');
    $('#uploadMusic').click();
  })
  // 音乐上传路径修改事件
  var uploadName='';
  var uploadType='';
  $('#uploadMusic').change(function (e) {
    var accept = e.target.getAttribute('data-accept');   
    var file = this.files[0];
    uploadName = file.name;
    uploadType = file.type;
    var fileSize = file.size, fileType = file.type;
    if (file.name.lastIndexOf('.') == -1) {
      //如果不存在"."  
      alert('路径不正确');
      return false;
    }
    if (fileType.indexOf(accept) == -1) {
      if (accept == 'text') {
        alert('歌词格式只支持text，请修改后缀名再上传');
      } else {
        alert('文件格式不正确');
      }
      return false;
    }
    if (accept == 'image') {
      $('.musicUploadForm').attr('action', '/node/uploadMusicImg');
      $('#addMusicForm #imgSrc').val(`${des}common/${file.name}`);
      setTimeout(()=>{
        $('#addMusicForm .imgSrc img').attr('src', `${des}common/${file.name}`);
      },1000)
    } else if (accept == 'audio') {
      $('.musicUploadForm').attr('action', '/node/uploadMusic');
      $('#addMusicForm #musicUrl').val(`${des2}${file.name}`);

    } else if (accept == 'text') {
      $('.musicUploadForm').attr('action', '/node/uploadMusic');
      $('#addMusicForm #LyricsUrl').val(`${des2}${file.name}`);
    }


    $('.uploadMusicBtn').click();
  })

  var bar = $('.barM');
  var percent = $('.percentM');
  var status = $('#statusM');
  var speed = $('.speedM');
  if(urlObj.area==3){
    $('.musicUploadForm').ajaxForm({
      beforeSerialize: function () {
        //alert("表单数据序列化前执行的操作！");
        //$("#txt2").val("java");//如：改变元素的值
        $('.musicUploadForm').attr('data-oldTime', Date.now());
        $('.musicUploadForm').attr('data-position', 0);
      },
      beforeSubmit: function () {
        //alert("表单提交前的操作");
        var filesize = $("#uploadMusic")[0].files[0].size / 1024 / 1024;
        if (filesize > 50) {
          alert('文件大小超过限制，最多50M');
          return false;
        }
        //if($("#txt1").val()==""){return false;}//如：验证表单数据是否为空
      },
      beforeSend: function (event) {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        bar.removeClass('success');
        percent.html(percentVal);
        speed.html('0.0 MB / S');
      },
      uploadProgress: function (event, position, total, percentComplete) {//上传的过程
        //position 已上传了多少
        //total 总大小
        //已上传的百分数
        var nowPosition = position - $('.musicUploadForm').attr('data-position');
        var time = Date.now() - $('.musicUploadForm').attr('data-oldTime');
        $('.musicUploadForm').attr('data-position', position);
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
        speed.html(`${parseFloat((nowPosition / 1024 / 1024) / (time / 100)).toFixed(1)} MB / S`);
        if(percentComplete>95 && uploadType == 'audio/mp3'){
          // 获取时间
          var audioElement = new Audio(`${des2}${uploadName}`);
          var duration;
          audioElement.addEventListener("loadedmetadata", function (_event) {
            duration = audioElement.duration;
            $('#addMusicForm #time').val(`${addZero(floor(duration / 60))}:${addZero(floor(duration % 60))}`);
          });
        }
      },
      success: function (data) {//成功
        var percentVal = '100%';
        bar.width(percentVal);
        bar.addClass('success');
        percent.html(percentVal);
        console.log(data);
      },
      error: function (err) {//失败
        console.log(err);
      },
      complete: function (xhr) {//完成
        status.html(xhr.responseText);
      }
    })
  }


  $('#newAddImg').click(()=>{
    //清空上一次
    $('#imgInputNew').val('');
    $('#imgInputNew').click();
  }); 
  $('#imgInputNew').on('change',function(){
    var file = this.files[0];
    var url = des + urlObj._id + '/' + file.name;
    $('.saveUpload').click();
    setTimeout(()=>{ appendImg(url); },400);
  })  
  $('.addNewSave').click(function(){
    $('#content').val($('#editNewView #contentNewText').html())
    alert('添加成功');
      setTimeout(()=>{toRrefresh();},400);
  })
  $('.editNewSave').click(function(){
    $('#editNewView #content').val($('#editNewView #contentNewText').html())
    alert('保存成功');
      setTimeout(()=>{history.go(0);},400);
  })
  $('#showNewView .editBtn').click(function(){
    $('#showNewView').hide();
    $('#editNewView').show();
    $('#editNewView').attr('action',`/node/editNew?_id=${urlObj._id}`);
  })
  $('.backLastPage').click(function(){
    if($('#showNewView').css('display')=='block')
    toRrefresh();
    else {
      // 还原
      $('#editNewView #animeTitle').val($('#showNewView #title').html())
      $('#editNewView #areaSelect').val($('#showNewView #area g').html())
      $('#editNewView #contentNewText').html($('#showNewView #contentNewText').html())
      $('#showNewView').show();
      $('#editNewView').hide();
    }
  })


  $('#usersTable .showP').click(function(){
    var text = $(this).html();
    if(text=="查看密码"){
      $(this).html('隐藏密码');
      $(this).parents('.tbody').find('.password .hidePwd').addClass('hide');
      $(this).parents('.tbody').find('.password .showPwd').removeClass('hide');
    }else if(text=="隐藏密码"){
      $(this).html('查看密码');
      $(this).parents('.tbody').find('.password .hidePwd').removeClass('hide');
      $(this).parents('.tbody').find('.password .showPwd').addClass('hide');
    }
  })






})